<!--
 * @Date: 2023-09-08 10:58:17
 * @LastEditTime: 2023-09-12 18:07:01
 * 介绍:
-->
<script lang="ts" setup>
import type { CinputImage } from "./index";
import type { ObjectFit, ObjectPosition } from "../../types/index";
import { showImagePreview } from "vant";
const props = withDefaults(
  defineProps<{
    accept?: string;
    maxLength?: number;
    imgFit?: ObjectFit;
    imgPosition?: ObjectPosition;
  }>(),
  {
    accept: "image/*",
  }
);
const maxLength = props.maxLength || 9;

const images = reactive<CinputImage[]>([]);
function change(e: Event) {
  const input = e.target as HTMLInputElement;
  const files = input.files;
  input.files = null;
  if (!files) return;
  for (let i = 0; i < files.length; i++) {
    if (images.length >= maxLength) return;
    const file = files[i];
    images.push({
      file,
      tempUrl: URL.createObjectURL(file),
    });
  }
  emit("change", images);
}

onUnmounted(() => {
  images.forEach((v) => {
    URL.revokeObjectURL(v.tempUrl);
  });
});
function delImage(i: number) {
  const file = images.splice(i, 1);
  file.forEach((v) => {
    URL.revokeObjectURL(v.tempUrl);
  });
  emit("change", images);
}
function previewImage(i: number) {
  showImagePreview({
    images: images.map((v) => v.tempUrl),
    startPosition: i,
    teleport: "body",
  });
}
const emit = defineEmits<{
  (e: "change", v: CinputImage[]): void;
}>();
</script>
<template>
  <Cgrid class="CinputImages" col="3" repeat="1fr">
    <CautoSquare
      v-for="(img, i) in images"
      :key="i"
      class="CinputImages_preview"
    >
      <div @click.stop="delImage(i)" class="CinputImages_del active">
        <van-icon class="CinputImages_del_icon" name="cross" />
      </div>
      <Rimage
        @click="previewImage(i)"
        :src="img.tempUrl"
        height="100%"
        width="100%"
        :fit="props.imgFit || 'contain'"
        :position="props.imgPosition || 'center'"
      />
    </CautoSquare>
    <CautoSquare v-if="images.length < maxLength">
      <CinputFile
        :accept="props.accept"
        @change="change"
        multiple
        height="100%"
        width="100%"
      />
    </CautoSquare>
  </Cgrid>
</template>
<style lang="scss" scoped>
.CinputImages {
  .CinputImages_preview {
    position: relative;
    .CinputImages_del {
      z-index: 10;
      position: absolute;
      right: 0;
      top: 0;
      --size: 32rem;
      height: var(--size);
      width: var(--size);
      background-color: var(--C-T1);
      border-radius: 0 0 0 999rem;
      .CinputImages_del_icon {
        position: absolute;
        top: 2rem;
        right: 2rem;
        font-size: calc(var(--size) / 2);
        color: var(--C-B1);
      }
    }
  }
}
</style>
